package com.atguigu.gmall.common.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author:lyd
 * @Date:2023/8/20 13:52
 * @Version:1.0
 * @Description 转换json
 **/
@Slf4j
public class JSONs {
    private static final ObjectMapper MAPPER=new ObjectMapper();

    public static String toJSONStr(Object obj) {
        String str=null;
        try {
            str = MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("json转换错误：" + e);
        }
        return str;
    }

    /**
     * 获取精确的返回值类型 如泛型套泛型 map<string,List<Integer>>
     * @param jsonStr
     * @param ref
     * @return
     * @param <T>
     */
    public static <T> T jsonToObj(String jsonStr, TypeReference<T> ref) {
        T t=null;
        try {
            t = MAPPER.readValue(jsonStr, ref);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return t;
    }

    /**
     * 获取简单的返回值类型
     * @param jsonStr
     * @param tClass
     * @return
     * @param <T>
     */
    public static <T> T jsonToObj(String jsonStr,Class<T> tClass) {
        T t=null;
        try {
            t = MAPPER.readValue(jsonStr, tClass);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return t;
    }
}
